//
//  PHDevicesViewController.m
//  PhnixHome
//
//  Created by Levy Xu on 2017/12/23.
//  Copyright © 2017年 Levy Xu. All rights reserved.
//

#import "PHDevicesViewController.h"
#import "GizManager.h"

@interface PHDevicesViewController ()
@property(nonatomic, strong) UIView *maskView;
@property(nonatomic, assign) BOOL maskHidden;
@end

@implementation PHDevicesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    WS(ws);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [GPHDeviceManager getBoundDevices:^(BOOL success) {
            [ws.tableView.mj_header endRefreshing];
            [ws deviceChanged:nil];
        }];
    }];
    [self.tableView.mj_header beginRefreshing];
}

- (void)setupNavigationItems {
    [super setupNavigationItems];
    self.title = NSLocalizedString(@"settings_device_manage", nil);
}

- (instancetype)initWithStyle:(UITableViewStyle)style {
    if (self = [super initWithStyle:style]) {
        [NNCDC addObserver:self selector:@selector(deviceChanged:) name:kDeviceCountChangedNotification object:nil];
        [NNCDC addObserver:self selector:@selector(deviceChanged:) name:kGizDeviceListChangedNotification object:nil];
    }
    return self;
}

-(void)deviceChanged:(NSNotification *)notification {
    [self.tableView reloadData];
    
    if ([GPHDeviceManager deviceList].count == 0 && [GizWifiSDK sharedInstance].deviceList.count == 0) {
        [self showEmptyViewWithText:NSLocalizedString(@"tips_no_device", nil) detailText:nil buttonTitle:nil buttonAction:nil];
        self.emptyView.textLabelFont = CodeFontMake(24);
        self.emptyView.verticalOffset = -60;
        
        if (_maskView) {
            [_maskView removeFromSuperview];
            _maskView = nil;
            _maskHidden = YES;
        }
    } else {
        [self hideEmptyView];
        
        if(!_maskHidden) {
            if(!_maskView) {
                _maskView = [[UIView alloc] initWithFrame:self.view.bounds];
                _maskView.backgroundColor = [UIColorGray5 colorWithAlphaComponent:0.4];
                [self.view addSubview:_maskView];
                
                CGFloat contentMinY = self.qmui_navigationBarMaxYInViewCoordinator;
                
                UIImageView *imageView = [[UIImageView alloc] initWithImage:UIImageMake(@"left_swipe")];
                imageView.frame = CGRectMake(SCREEN_WIDTH / 2 - 40, contentMinY + 50, 80, 80);
                [_maskView addSubview:imageView];
                
                QMUILabel *label = [[QMUILabel alloc] initWithFrame:CGRectMake(20, imageView.qmui_bottom + 5, SCREEN_WIDTH - 40, 24)];
                label.font = CodeFontMake(18);
                label.textColor = GQDThemeManager.currentTheme.themeTintColor;
                label.textAlignment = NSTextAlignmentCenter;
                label.text = NSLocalizedString(@"tips_left_swipe_do_more", nil);
                [_maskView addSubview:label];
                
                UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
                [_maskView addGestureRecognizer:gesture];
            }
            [self.view bringSubviewToFront:_maskView];
        }
    }
}

-(void)tapAction:(UITapGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateEnded) {
        if (_maskView) {
            [_maskView removeFromSuperview];
            _maskView = nil;
            _maskHidden = YES;
        }
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return [GizWifiSDK sharedInstance].deviceList.count;
    } else {
        return [GPHDeviceManager deviceList].count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001f;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001f;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identi = @"cell";
    QMUITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identi];
    if (!cell) {
        cell = [[QMUITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identi];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.textLabel.font = KKFontMake(16);
        cell.detailTextLabel.font = KKFontMake(14);
        QMUILabel *label = [[QMUILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 20)];
        label.font = KKFontMake(16);
        label.textAlignment = NSTextAlignmentRight;
        cell.accessoryView = label;
    }
    if (indexPath.section == 0 && indexPath.row == 0) {
        cell.qmui_borderPosition = QMUIBorderViewPositionTop | QMUIBorderViewPositionBottom;
    } else {
        cell.qmui_borderPosition = QMUIBorderViewPositionBottom;
    }
    if (indexPath.section == 1) {
        GizWifiDevice *model = [GizWifiSDK sharedInstance].deviceList[indexPath.row];
        cell.imageView.image = [[model displayImage] qmui_imageResizedInLimitedSize:CGSizeMake(60, 60)];
        cell.textLabel.text = [model deviceName];
        cell.detailTextLabel.text = model.did;
        
        QMUILabel *label = (QMUILabel *)[cell accessoryView];
        label.textColor = model.netStatusColor ;
        label.text = model.netStatusString;
    } else {
        PHDevice *model = [GPHDeviceManager deviceList][indexPath.row];
        cell.imageView.image = [[model displayImage] qmui_imageResizedInLimitedSize:CGSizeMake(60, 60)];
        cell.textLabel.text = model.device_nick_name;
        cell.detailTextLabel.text = model.device_code;
        
        QMUILabel *label = (QMUILabel *)[cell accessoryView];
        if ([model.is_online isEqualToString:ONLINE]) {
            label.textColor = UIColorGreen;
            label.text = NSLocalizedString(@"net_online", nil);
        } else if ([model.is_online isEqualToString:OFFLINE]) {
            label.textColor = UIColorRed;
            label.text = NSLocalizedString(@"net_offline", nil);
        } else if ([model.is_online isEqualToString:UNACTIVE]) {
            label.textColor = UIColorYellow;
            label.text = NSLocalizedString(@"net_unactive", nil);
        } else if ([model.is_online isEqualToString:UNFINDED]) {
            label.textColor = UIColorYellow;
            label.text = NSLocalizedString(@"net_unfound", nil);
        } else if ([model.is_online isEqualToString:UNBOUND]) {
            label.textColor = UIColorYellow;
            label.text = NSLocalizedString(@"net_unbind", nil);
        } else {
            label.textColor = UIColorGray;
            label.text = model.is_online;
        }
    }
    return cell;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

-(NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *layTopRowAction1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:NSLocalizedString(@"btn_delete", nil) handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        if (indexPath.section == 1) {
            GizWifiDevice *model = [GizWifiSDK sharedInstance].deviceList[indexPath.row];
            [KKAlert alertWithTitle:NSLocalizedString(@"btn_delete", nil) message:NSLocalizedString(@"tips_delete_device", nil) cancel:^{
                
            } ok:^{
                [[GizWifiSDK sharedInstance] unbindDevice:GGizManager.token.uid token:GGizManager.token.token did:model.did];
            }];
        } else {
            PHDevice *model = [GPHDeviceManager deviceList][indexPath.row];
            [KKAlert alertWithTitle:NSLocalizedString(@"btn_delete", nil) message:NSLocalizedString(@"tips_delete_device", nil) cancel:^{
                
            } ok:^{
                [GPHDeviceManager removeDevice:model];
            }];
        }
        [tableView setEditing:NO animated:YES];
    }];
    layTopRowAction1.backgroundColor = UIColorRed;
    
    UITableViewRowAction *layTopRowAction2 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:NSLocalizedString(@"title_edit_name", nil) handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        WS(ws);
        if (indexPath.section == 1) {
            GizWifiDevice *model = [GizWifiSDK sharedInstance].deviceList[indexPath.row];
            [KKAlert inputWithTitle:NSLocalizedString(@"title_edit_name", nil) text:model.alias placeholder:NSLocalizedString(@"tips_input_name", nil) ok:^(NSString *string) {
                
                [model setCustomInfo:nil alias:string];
                
            }];
        } else {
            PHDevice *model = [GPHDeviceManager deviceList][indexPath.row];
            [KKAlert inputWithTitle:NSLocalizedString(@"title_edit_name", nil) text:model.device_nick_name placeholder:NSLocalizedString(@"tips_input_name", nil) ok:^(NSString *string) {
                
                [model modifyNickname:string finish:^(BOOL success) {
                    if (success) {
                        model.device_nick_name = string;
                        [ws.tableView reloadData];
                    }
                }];
            }];
        }
        [tableView setEditing:NO animated:YES];
    }];
    layTopRowAction2.backgroundColor = UIColorGreen;
    return @[ layTopRowAction1, layTopRowAction2 ];
}

@end
